package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.msg.bean.WorkContent;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IVUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayer;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayerStandard;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配音详情页面
 */
public class DubVideoDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "DubVideoDetailActivity";
    private KHBVideoPlayerStandard mKHBVideoPlayerStandard;
    private ImageView ivVideoPlay;
    private TextView tvDubVideoName, tvDubVideoDetail;


    /**
     * 作业资源结构体
     */
    private WorkContent mWorkContent;
    /**
     * 视频本地保存地址
     */
    private String localVideoPath, localAudioPath, title;
    /**
     * 资源是否加载完成
     */
    private boolean isWorkContent = false;

    /**
     * 背景音是否需要下载
     */
    private boolean isNeedDownAudio = false;
    /**
     * 作业id（练习模式为“”）
     */
    private String workId = "";

    /**
     * 服务id
     */
    private int workType = 0;
    /**
     * 作业的班级id
     */
    private String classId = "0";

    /**
     * 作业内容id
     */
    private int contentId = 0;

    @Override
    protected int setView() {
        return R.layout.activity_dub_video_detail;
    }

    @Override
    protected void findViews() {
        mKHBVideoPlayerStandard = findViewById(R.id.khb_content_video);
        ivVideoPlay = findViewById(R.id.iv_video_play);
        tvDubVideoName = findViewById(R.id.tv_dub_video_name);
        tvDubVideoDetail = findViewById(R.id.tv_dub_video_detail);

    }

    @Override
    protected void initEvent() {
        ivVideoPlay.setOnClickListener(this);

    }

    @Override
    protected void init() {
        mKHBVideoPlayerStandard.setNormalView(true);
        initData();
    }

    protected void initData() {
        Intent intent = getIntent();
        mWorkContent = (WorkContent) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        classId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
        contentId = intent.getIntExtra(IntentFlag.INTENT_FLAG_CONTENTID, 0);
        initView();
    }

    private void initView() {
        title = "预览";
        setTitleText(title);
        if (mWorkContent != null) {
            tvDubVideoName.setText(mWorkContent.getResourceName());
            workType = mWorkContent.getWorkType();
            tvDubVideoDetail.setText(mWorkContent.getDetails());
            isWorkContent = true;
            initVideoView();
        } else {
            getDubVideoDetailFromNet();
        }
    }

    @Override
    protected void loadData() {
//        getDubVideoDetailFromNet();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        KHBVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_video_play) {
            //播放
            mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
        }
    }


    private void showProgressLoading() {
        showMiddleProgressBar(title);
    }

    private void dismissProgress() {
        hideMiddleProgressBar();
    }

    public void getDubVideoDetailFromNet() {
        showProgressLoading();
        EpaperDao.getInstance().getDubVideoDetail(mWorkContent.getVersionId(), new BaseExtCallBack(DubVideoDetailActivity.this) {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                dismissProgress();
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                dismissProgress();
            }

            @Override
            public void success(Object data) {
                dismissProgress();
                try {
                    if (data != null && data instanceof WorkContent) {
                        mWorkContent = (WorkContent) data;
                        if ("".equals(mWorkContent.getBgAudioUrl())) {
                            mWorkContent.setBgAudioUrl("https://rimg3.ciwong.net/6v68/tools/audios/bgTemplate.mp3");
                        }
                        if (workType != 0) {
                            mWorkContent.setWorkType(workType);
                        }
                        tvDubVideoDetail.setText(mWorkContent.getDetails());
                        isWorkContent = true;
                        initVideoView();
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });
    }

    /**
     * 加载视频视图
     */
    private void initVideoView() {
        IVUtils.setImageWidth200(mKHBVideoPlayerStandard.thumbImageView, mWorkContent.getCover());
        showGetPermissDialog();
    }

    /**
     * 设置视频播放资源
     */
    private void initDataView() {
        localVideoPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(mWorkContent.getVideoUrl());
        File targetFile = new File(localVideoPath);
        if ("".equals(mWorkContent.getBgAudioUrl())) {
            mWorkContent.setBgAudioUrl("https://rimg3.ciwong.net/6v68/tools/audios/bgTemplate.mp3");
        }
        if (mWorkContent.getBgAudioUrl() != null && !"".equals(mWorkContent.getBgAudioUrl())) {
            localAudioPath = ESystem.getDubingVideoPath() + File.separator + StringUtils.md5(mWorkContent.getBgAudioUrl()) + ".mp3";
            File targetAudioFile = new File(localAudioPath);
            if (!targetAudioFile.exists()) {
                isNeedDownAudio = true;
            } else {
                isNeedDownAudio = false;
            }
        }
        if (targetFile.exists()) {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(localVideoPath, KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
        } else {
            mKHBVideoPlayerStandard.setplsyModeUrlUp(mWorkContent.getVideoUrl(), KHBVideoPlayer.SCREEN_LAYOUT_LIST, KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
        }
        mKHBVideoPlayerStandard.startVideo(KHBVideoPlayer.PLAY_MODE_UNMUTE);
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.read_and_write_local_storage_permissions));
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                initDataView();
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            initDataView();
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_REQUEST_WRITESD_PERMISSION:
                    initDataView();
                    break;
            }
        }
    }

}